<script setup lang="ts">
import { reqHasTrademark, reqDeleteTrademark, reqAddOrUpdateTrademark } from '@/api/product/trademark'
import type { ITrademark } from '@/api/product/trademark/types'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
let currentPage = ref<number>(1)
let pageSize = ref<number>(3)
let totalNum = ref<number>(138)
let data = ref<ITrademark[]>([])
let formRef = ref()
const DialogVisible = ref<boolean>(false)
const formTrademarkData = ref<ITrademark>({
  tmName: '',
  logoUrl: ''
})
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  // 自定义校验规则 校验成功 callBack(), 失败 callBack(new Error('失败提示信息'))
  if (value) {
    callBack()
  } else {
    callBack(new Error('Logo图片不能缺少'))
  }
}
const rules = {
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 3, max: 20, message: '字符长度应在3-20位之间', trigger: 'blur' }
  ],
  // 图片上传 无法触发校验，在表单整体校验
  logoUrl: [{ required: true, validator: validatorLogoUrl }]
}
const sizeChange = (value: number) => {
  pageSize.value = value // page-size 没有v-model 需要赋值
  currentPage.value = 1
  getHasTrademark()
}

const getHasTrademark = async () => {
  const res = await reqHasTrademark(currentPage.value, pageSize.value)
  if (res.code === 200) {
    totalNum.value = res.data.total
    data.value = res.data.records
  }
}
onMounted(() => {
  getHasTrademark()
})

const AddTrademark = () => {
  // 表单对象还没有 报错
  // formRef.value?.resetFields() // 重置表单和校验
  nextTick(() => formRef.value.resetFields())
  formTrademarkData.value = { tmName: '', logoUrl: '' }
  DialogVisible.value = true
}
const EditTrademark = (row: ITrademark) => {
  DialogVisible.value = true
  formTrademarkData.value.id = row.id
  formTrademarkData.value.tmName = row.tmName
  formTrademarkData.value.logoUrl = row.logoUrl
  // 移除校验结果
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

const confirm = async () => {
  // 触发表单整体校验
  // await调用这个方法校验，等待成功后执行后面，无成功不执行后续代码
  await formRef.value.validate() // 未处理的错误
  // let checkResult = await formRef.value.validate().catch(() => {})
  // if (!checkResult) return
  DialogVisible.value = false
  const res = await reqAddOrUpdateTrademark(formTrademarkData.value)
  if (res.code === 200) {
    ElMessage.success(formTrademarkData.value.id ? '修改品牌成功' : '添加品牌成功')
    getHasTrademark()
  } else {
    ElMessage.error(formTrademarkData.value.id ? '修改品牌失败' : '添加品牌失败')
    throw new Error(formTrademarkData.value.id ? '修改品牌失败' : '添加品牌失败')
  }
}

const DeleteTrademark = async (id: number) => {
  // await ElMessageBox.confirm('确认删除品牌吗？', '删除询问', {
  //   confirmButtonText: '确认',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).catch(() => {
  //   ElMessage.info('已取消！')
  //   return new Promise(() => {})
  // })
  let res = await reqDeleteTrademark(id)
  if (res.code === 200) {
    ElMessage.success('品牌删除成功')
    getHasTrademark()
  } else {
    ElMessage.error('品牌删除失败')
    throw new Error('品牌删除失败')
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  console.log(URL.createObjectURL(uploadFile.raw!)) // 上传文件本机内存中的地址
  formTrademarkData.value.logoUrl = response.data
  // 清除图片校验错误信息
  formRef.value.clearValidate('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (['image/jpeg', 'image/png', 'image/gif'].indexOf(rawFile.type) < 0) {
    ElMessage.error('只能上传图像格式文件!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过 2MB!')
    return false
  }
  return true
}
</script>

<template>
  <div>
    <el-card>
      <el-button type="primary" icon="Plus" @click="AddTrademark">添加品牌</el-button>
      <el-table border stripe style="margin: 10px 0" :data="data">
        <el-table-column label="序号" :width="80" align="center" type="index"> </el-table-column>
        <el-table-column label="品牌名称" prop="tmName" align="center"> </el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template v-slot="{ row }">
            <el-image style="width: 100px; height: 100px" :src="row.logoUrl">
              <template #error>
                <el-image fit="scale-down" style="width: 100px; height: 100px" :src="'http://' + row.logoUrl" />
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template v-slot="{ row }">
            <el-button type="primary" icon="Edit" @click="EditTrademark(row)"></el-button>
            <!-- <el-button type="danger" icon="Delete" @click="DeleteTrademark(row.id)"></el-button> -->
            <el-popconfirm title="确认删除该品牌吗?" width="200px" icon="Delete" icon-color="#626AEF" @confirm="DeleteTrademark(row.id)">
              <template #reference>
                <el-button type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      @size-change="sizeChange"
      @current-change="getHasTrademark"
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[3, 10, 20, 50]"
      layout="prev, pager, next, jumper,->, sizes,total"
      :total="totalNum"
      background
      style="margin-top: 10px"
      :pager-count="7"
    >
    </el-pagination>
    <el-dialog
      :title="formTrademarkData.id ? '修改品牌' : '添加品牌'"
      v-model="DialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="formTrademarkData" :rules="rules" ref="formRef" label-width="90px" :inline="false" size="large" style="width: 80%">
        <el-form-item label="品牌" prop="tmName">
          <el-input v-model="formTrademarkData.tmName" />
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formTrademarkData.logoUrl" :src="formTrademarkData.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="DialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
